package ita.class1.group2.supermarket.common.captain.handler;

import ita.class1.group2.supermarket.common.util.JsonUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ResponseHandler {

    public void handle(HttpServletResponse response, Object result) throws Exception {
        if (result != null) {
            if (result instanceof File) {
                File file = (File) result;

                InputStream is = new FileInputStream(file);
                OutputStream os = response.getOutputStream();

                int len = -1;
                byte[] buff = new byte[1024];
                while ((len = is.read(buff)) != -1) {
                    os.write(buff, 0, len);
                }

                is.close();
                os.flush();
            } else if (result instanceof String) {
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write(((String) result));
            } else {
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JsonUtil.obj2json(result));
            }
        }
    }

}
